package com.iwop.moto.service.impl;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.comm.SystemConstant;
import com.iwop.moto.dao.FProceedsRecordDao;
import com.iwop.moto.exceptions.MyException;
import com.iwop.moto.model.*;
import com.iwop.moto.model.PO.PromotionVo;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.stringUtil.BigDecimalUtil;
import com.iwop.moto.utils.stringUtil.ObjectId;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Created by huyuangui on 2016/7/7.
 */
@Service("userService")
public class UserServiceImpl extends BaseService implements UserService {

    private Logger logger = Logger.getLogger(UserServiceImpl.class);


    @Autowired
    private MPaymentService mPaymentService;
    @Autowired
    private FOrderServiceService orderServiceService;
    @Autowired
    private MOrderPurchaseService mOrderPurchaseService;

    @Autowired
    private MCouponService mCouponService;

    @Autowired
    MGPOrderService mgpOrderService;

    /**
     * 根据用户密码或者SID获取用户
     */
    public static String findById = "com.iwop.moto.dao.UserMapper.findById";
    public static String findByParam = "com.iwop.moto.dao.UserMapper.findByParam";
    public static String insert = "com.iwop.moto.dao.UserMapper.insert";
    public static String update = "com.iwop.moto.dao.UserMapper.update";
    public static String updatebyUserType = "com.iwop.moto.dao.UserMapper.updatebyUserType";
    public static String getLastUser = "com.iwop.moto.dao.UserMapper.getLastUser";
    public static String checkUserByTel = "com.iwop.moto.dao.UserMapper.checkUserByTel";
    public static String checkUserByOpenId = "com.iwop.moto.dao.UserMapper.checkUserByOpenId";
    public static String findUserByOpenId = "com.iwop.moto.dao.UserMapper.findUserByOpenId";
    public static String findUserByPromotionCode = "com.iwop.moto.dao.UserMapper.findUserByPromotionCode";
    public static String insertUser = "com.iwop.moto.dao.UserMapper.insertUser";
    public static String updateUser = "com.iwop.moto.dao.UserMapper.updateUser";
    public static String findUserAndStoreByUserId = "com.iwop.moto.dao.UserMapper.findUserAndStoreByUserId";
    public static String findUserByPromotion = "com.iwop.moto.dao.UserMapper.findUserByPromotion";
    public static String updateUserAuditStatus = "com.iwop.moto.dao.UserMapper.updateUserAuditStatus";
    public static String findUserBySid = "com.iwop.moto.dao.UserMapper.findUserBySid";
    public static String findUsersByAuditStatus = "com.iwop.moto.dao.UserMapper.findUsersByAuditStatus";
    public static String findUsersByTel = "com.iwop.moto.dao.UserMapper.findUsersByTel";
    public static String findCountMemberArea = "com.iwop.moto.dao.UserMapper.findCountMemberArea";
    public static String findAdminAuditList = "com.iwop.moto.dao.UserMapper.findAdminAuditList";
    public static String delete = "com.iwop.moto.dao.UserMapper.delete";
    public static String findUsersByDistrict = "com.iwop.moto.dao.UserMapper.findUsersByDistrict";
    public static String findUsersByDistrictCount = "com.iwop.moto.dao.UserMapper.findUsersByDistrictCount";
    public static String findServiceCountByDistrict = "com.iwop.moto.dao.UserMapper.findServiceCountByDistrict";
    public static String findLoginByUserType = "com.iwop.moto.dao.UserMapper.findLoginByUserType";
    public static String findAdminAduitCount = "com.iwop.moto.dao.UserMapper.findAdminAduitCount";
    public static String findServiceAduitCount = "com.iwop.moto.dao.UserMapper.findServiceAduitCount";
    public static String findAdminAduitHistoryCount = "com.iwop.moto.dao.UserMapper.findAdminAduitHistoryCount";
    public static String updateAuditDescribe = "com.iwop.moto.dao.UserMapper.updateAuditDescribe";
    public static String getUserMapBySid = "com.iwop.moto.dao.UserMapper.selectUserMapBySid";
    public static String updateUnionId = "com.iwop.moto.dao.UserMapper.updateUnionId";
    public static String updateUserRmoneyBySid = "com.iwop.moto.dao.UserMapper.updateUserRmoneyBySid";
    public static String findUserTotalUserType = "com.iwop.moto.dao.UserMapper.selectUserTotalUserType";
    public static String getTotalUserType = "com.iwop.moto.dao.UserMapper.selectCountUserRepair";
    public static String getTotalUser = "com.iwop.moto.dao.UserMapper.getTotalUser";
    public static String getUserBySid = "com.iwop.moto.dao.UserMapper.getUserBySid";
    public static String updatePopular = "com.iwop.moto.dao.UserMapper.updatePopular";
    public static String updateMagicBean = "com.iwop.moto.dao.UserMapper.updateMagicBean";
    public static String updateUserByDeviceId = "com.iwop.moto.dao.UserMapper.updateUserByDeviceId";
    public static String updateUserBytel = "com.iwop.moto.dao.UserMapper.updateUserBytel";
    public static String updateRedPacketBySid = "com.iwop.moto.dao.UserMapper.updateRedPacketBySid";
    public static String updateRmoneyAndRedPacketByid = "com.iwop.moto.dao.UserMapper.updateRmoneyAndRedPacketByid";
    public static String getUserForDate = "com.iwop.moto.dao.UserMapper.getUserForDate";
    public static String findAdminAuditListFromDate = "com.iwop.moto.dao.UserMapper.findAdminAuditListFromDate";
    public static String deleteUser = "com.iwop.moto.dao.UserMapper.deleteUser";
    public static String findEnterStoresListByMap = "com.iwop.moto.dao.UserMapper.findEnterStoresListByMap";
    public static String findEnterStoresListDetailByMap = "com.iwop.moto.dao.UserMapper.findEnterStoresListDetailByMap";
    public static String findenterStoresExportListByMap = "com.iwop.moto.dao.UserMapper.findenterStoresExportListByMap";
    public static String findEnterStoresListByMapCount = "com.iwop.moto.dao.UserMapper.findEnterStoresListByMapCount";
    @Autowired
    private MPromotionService promotionService;
    @Autowired
    private FProceedsRecordDao proceedsDao;

    /***
     * 采用username 和pwd密码验证登录
     * @param user
     * @return user
     */
    public User login(User user) {
//        if(user!=null && StringUtils.isNotEmpty(user.getTel())) {
//            Map<String,String> map=new HashMap<String,String>();
//            map.put("tel",user.getTel());
//            User userTemp=getSqlSession().selectOne(findById,map);
//            if(userTemp!=null && userTemp.getPwd().equals(user.getPwd())){
//                return userTemp;
//            }
//        }

        return getSqlSession().selectOne("getUserByEntity", user);
    }

    @Override
    public void register(User user) {
        getSqlSession().insert(insert, user);
    }

    @Override
    public User findUserByUser(User user) {
        if (user == null) {
            return null;
        }
        if (StringUtils.isNotEmpty(user.getUsername()) || StringUtils.isNotEmpty(user.getTel()) || StringUtils.isNotEmpty(user.getSid())) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("sid", user.getSid());
            map.put("tel", user.getTel());
            map.put("userType", user.getUserType());
            map.put("username", user.getUsername());
            User userTemp = getSqlSession().selectOne(findById, map);
            return userTemp;
        }
        return null;
    }

    @Override
    public User findUserByParam(User user) {
        if (user == null) {
            return null;
        }
//        if(StringUtils.isNotEmpty(user.getUsername()) || StringUtils.isNotEmpty(user.getTel()) || StringUtils.isNotEmpty(user.getSid())) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("sid", user.getSid());
        map.put("tel", user.getTel());
        map.put("userType", user.getUserType());
        map.put("username", user.getUsername());
        User userTemp = getSqlSession().selectOne(findByParam, map);
        return userTemp;
    }
//        return null;


    @Override
    public User save(User user) {
        if (user == null) {
            return null;
        }
        User userTemp = findUserByUser(user);
        if (userTemp == null) {
            getSqlSession().insert(insert, user);
            userTemp = getLastUser();
            return userTemp;
        } else {
            getSqlSession().update(update, user);
            userTemp = findUserByUser(user);
            return userTemp;
        }

    }

    @Override
    public User updatebyUserType(User user) {
        if (user == null) {
            return null;
        }
        getSqlSession().update(updatebyUserType, user);
        User userTemp = findUserByUser(user);
        return userTemp;
    }

    @Override
    public User getLastUser() {
        User user = getSqlSession().selectOne(getLastUser, null);
        return user;
    }

    @Override
    public User getUserBySid(String sid) {
        return getSqlSession().selectOne(getUserBySid, sid);
    }

    public User findLoginByUserType(User user) {
        return getSqlSession().selectOne(findLoginByUserType, user);
    }

    /**
     * @功能: 校验微信的openid是否注册过
     */
    public boolean checkUserByOpenId(SuperRecordModel SRModel) {
        SuperRecordModel srm = getSqlSession().selectOne(checkUserByOpenId, SRModel);
        return Integer.valueOf(srm.getString("wx_count")) == 0;
    }

    /**
     * @功能: 校验用户手机号是否注册过
     */
    public boolean checkUserByTel(SuperRecordModel SRModel) {
        SuperRecordModel srm = getSqlSession().selectOne(checkUserByTel, SRModel);
        return (Long) srm.get("tel_count") == 0l;
    }

    /**
     * @功能: 根据微信openid获取用户信息
     */
    public SuperRecordModel findUserByOpenId(SuperRecordModel SRModel) {
        return getSqlSession().selectOne(findUserByOpenId, SRModel);
    }

    /**
     * @功能: 根据推广码查找用户信息
     */
    public SuperRecordModel findUserByPromotionCode(String promotion_code) {
        return getSqlSession().selectOne(findUserByPromotionCode, promotion_code);
    }

    /**
     * @功能: 新增用户
     */
    public void insertUser(SuperRecordModel SRModel) {
        getSqlSession().insert(insertUser, SRModel);
    }

    /**
     * @功能: 修改用户信息
     */
    public void updateUser(SuperRecordModel SRModel) {
        getSqlSession().insert(updateUser, SRModel);
    }

    /**
     * @功能: 团队成员详情信息
     */
    public SuperRecordModel findUserAndStoreByUserId(String userId) {
        return getSqlSession().selectOne(findUserAndStoreByUserId, userId);
    }

    /**
     * @功能: 查询服务商下面的一级、二级团队成员
     */
    public List<SuperRecordModel> findUserByPromotion(SuperRecordModel SRModel) {
        return getSqlSession().selectList(findUserByPromotion, SRModel);
    }

    /**
     * @功能: 更新用户审核状态
     * @审核状态: [0:未审核][1:服务商通过][-1:服务商拒绝][2:平台通过][-2:平台拒绝]
     */
    public void updateUserAuditStatus(SuperRecordModel SRModel) {
        getSqlSession().update(updateUserAuditStatus, SRModel);
    }

    /**
     * @param SRModel
     * @功能: 根据主键获取用户信息
     */
    public SuperRecordModel findUserBySid(SuperRecordModel SRModel) {
        return getSqlSession().selectOne(findUserBySid, SRModel);
    }

    /**
     * @param SRModel
     * @功能: 根据审核类型获取用户
     * @审核状态: [0:未审核][1:服务商通过][-1:服务商拒绝][2:平台通过][-2:平台拒绝]
     */
    public List<SuperRecordModel> findUsersByAuditStatus(SuperRecordModel SRModel) {
        return getSqlSession().selectList(findUsersByAuditStatus, SRModel);
    }

    /**
     * 根据手机号查询用户列表
     * @param tel
     * @return
     */
    public List<User> findUsersByTel(String tel) {
        return getSqlSession().selectList(findUsersByTel, tel);
    }

    public Integer findCountMemberArea(SuperRecordModel SRModel) {
        SRModel = getSqlSession().selectOne(findCountMemberArea, SRModel);
        Long count_num = (Long) SRModel.get("count_num");
        return count_num.intValue();
    }

    @Override
    public void upUserBirthday(SuperRecordModel SRModel) {
        getSqlSession().update("com.iwop.moto.dao.UserMapper.upUserBirthday", SRModel);
    }

    /**
     * @功能: 根据用户类型和审核状态获取数据
     * @param: user_type  用户类型
     * @param: audit_flag 审核状态
     */
    public List<SuperRecordModel> findAdminAuditList(SuperRecordModel SRModel) {
        return getSqlSession().selectList(findAdminAuditList, SRModel);
    }

    /**
     * 删除用户
     *
     * @param sid 主键
     */
    public void delete(String sid) {
        getSqlSession().delete(delete, sid);
    }

    /**
     * @param SRModel
     * @author: liuwb by 2016-09-02 on create
     * @功能: 服务商团队人员/审核成员
     * 1 [省级]服务商 > 所属[市级]的服务商 level 2
     * 2 [市级]服务商 > 所属[区/县级]的服务商 level 3
     * 3 [区/县]服务商 > 所属[镇/乡/街道]的服务商 level 4
     * 4 [镇/乡/街道]服务商 > 所属[镇/乡/街道]的维修店 level 0 无(维修店)
     * @说明: 根据服务商等级获取下一级成员;
     * 【省/直辖市】 >> 【市级】 >> 【区/县】 >> 【镇/乡/街道】 >> 【镇/乡/街道所属维修店】
     * @SRModel auditFlag 审核[0:未审核][1:服务商通过][-1:服务商拒绝][2:平台通过][-2:平台拒绝]
     * @SRModel level 原服务商的等级加一 level + 1
     * @SRModel province 省级/直辖市
     * @SRModel city 市区
     * @SRModel area 区/县级
     * @SRModel town 镇/乡/街道
     */
    public List<SuperRecordModel> findUsersByDistrict(SuperRecordModel SRModel) {
        return getSqlSession().selectList(findUsersByDistrict, SRModel);
    }

    public Long findUsersByDistrictCount(SuperRecordModel SRModel) {
        return getSqlSession().selectOne(findUsersByDistrictCount, SRModel);
    }

    /**
     * @param SRModel
     * @author: liuwb by 2016-09-03 on create
     * @功能: 根据区域获取服务商数量
     * @SRModel province 省级/直辖市
     * @SRModel city 市区
     * @SRModel area 区/县级
     * @SRModel town 镇/乡/街道
     */
    public Long findServiceCountByDistrict(SuperRecordModel SRModel) {
        return getSqlSession().selectOne(findServiceCountByDistrict, SRModel);
    }

    /**
     * @功能: 统计平台审核中数量
     * @日期: liuwb by 2016-09-19 create
     */
    public Long findAdminAduitCount() {
        return getSqlSession().selectOne(findAdminAduitCount);
    }

    /**
     * @功能: 统计服务商审核中数量
     * @日期: liuwb by 2016-09-19 create
     */
    public Long findServiceAduitCount() {
        return getSqlSession().selectOne(findServiceAduitCount);
    }

    /**
     * @功能: 查询统计平台审核历史数量
     * @日期: liuwb by 2016-09-19 create
     */
    public Long findAdminAduitHistoryCount() {
        return getSqlSession().selectOne(findAdminAduitHistoryCount);
    }

    /**
     * @功能: 更新user审核描述
     * @日期: liuwb by 2016-09-19 create
     */
    public void updateAuditDescribe(SuperRecordModel SRModel) {
        getSqlSession().update(updateAuditDescribe, SRModel);
    }

    @Override
    public User getUserMapBySid(SuperRecordModel SRModel) {
        return getSqlSession().selectOne(getUserMapBySid, SRModel);
    }

    public void updateUnionId(SuperRecordModel SRModel) {
        getSqlSession().update(updateUnionId, SRModel);
    }

    @Override
    public List<SuperRecordModel> findUserTotalUserType(SuperRecordModel SRModel) {
        return getSqlSession().selectList(findUserTotalUserType, SRModel);
    }

    @Override
    public List<SuperRecordModel> getTotalUserType(SuperRecordModel SRModel) {
        return getSqlSession().selectList(getTotalUserType, SRModel);
    }

    /**
     * @param user
     * @功能: 更新用户金额
     */
    public void updateUserRmoneyBySid(User user) {
        getSqlSession().update(updateUserRmoneyBySid, user);
    }

    @Override
    public List<User> findUserAll() {
        return getSqlSession().selectList(getTotalUser);
    }

    @Override
    public void updatePopular(SuperRecordModel srModel) {
        getSqlSession().update(updatePopular, srModel);
    }

    @Override
    public void updateMagicBean(SuperRecordModel srModel) {
        getSqlSession().update(updateMagicBean, srModel);
    }

    @Override
    public void updateUserByDeviceId(User user) {
        getSqlSession().update(updateUserByDeviceId, user);
    }

    @Override
    public void updateUserByTel(User user) {
        getSqlSession().update(updateUserBytel, user);
    }

    @Override
    public void updateRedPacketBySid(User userBySid) {
        getSqlSession().update(updateRedPacketBySid, userBySid);
    }

    @Override
    public void updateRmoneyAndRedPacketByid(User user) {
        getSqlSession().update(updateRmoneyAndRedPacketByid, user);
    }

    @Override
    public List<SuperRecordModel> getUserForDate(SuperRecordModel srModel) {
        return getSqlSession().selectList(getUserForDate, srModel);
    }

    @Override
    public List<SuperRecordModel> findAdminAuditListFromDate(SuperRecordModel srm) {
        return getSqlSession().selectList(findAdminAuditListFromDate, srm);
    }

    @Override
    public void deleteUser(String sid) {
        getSqlSession().delete(deleteUser, sid);
    }


    /**
     * 余额支付
     *
     * @param user             用户
     * @param superRecordModel
     * @return
     */
    @Override
    @Transactional
    public void balanceHandle(User user, SuperRecordModel superRecordModel) throws MyException {
        String orderId = superRecordModel.getString("orderId");
        String seller_user_id = superRecordModel.getString("seller_user_id");
        String coupon_id = superRecordModel.getString("coupon_id");
        String payType = superRecordModel.getString("payType");
        Double pmoney = (Double) superRecordModel.get("pmoney");
        String brokerage = superRecordModel.getString("brokerage");
        String content = superRecordModel.getString("content");
        BigDecimal orderMoney = (BigDecimal) superRecordModel.get("orderMoney");
        String csid = superRecordModel.getString("csid");

        Double beforMoney = user.getRmoney();//交易前余额
        double afterMoney = BigDecimalUtil.getSubtract(beforMoney, pmoney);//扣除支付金额后的用户余额
        user.setRmoney(afterMoney);//设置余额
        Double numTwo = Double.valueOf(brokerage);
        user.setRedPacket(BigDecimalUtil.getSubtract(user.getRedPacket(), numTwo));//扣除佣金

        //持久化更新用户
        updateRmoneyAndRedPacketByid(user);


        //添加收款方金额
        User sellerUser = this.getUserBySid(seller_user_id);
        Double sellerUserBeforRmoney = sellerUser.getRmoney();
        Double uafterMoney = orderMoney.doubleValue() - orderMoney.doubleValue() * Comm.BROKERAGE;//单笔收取手续费后交易金额
        sellerUser.setRmoney(sellerUser.getRmoney() + uafterMoney);
        this.updateUserRmoneyBySid(sellerUser);

        //插入交易记录
        MPayment mPayment = new MPayment();
        mPayment.setPayId(ObjectId.UUID());
        mPayment.setBuyerUserId(user.getSid());
        mPayment.setSellerUserId(seller_user_id);
        mPayment.setMchType("BALANCE");//余额交易类型
        mPayment.setMchId("MB");
        mPayment.setCouponId(coupon_id);
        mPayment.setBrokerage(numTwo);
        mPayment.setOutTradeNo(orderId);
        mPayment.setPayTradeNo(ObjectId.UUID());
        mPayment.setPayType(payType);//余额支付
        double payFree = BigDecimalUtil.getMultiply(orderMoney.doubleValue(), Comm.BROKERAGE);
        mPayment.setPayFee(payFree);
        mPayment.setPayMoney(BigDecimalUtil.getSubtract(orderMoney.doubleValue(), payFree));
        mPayment.setOriginalTmoney(sellerUserBeforRmoney);
        mPayment.setModifyTmoney(sellerUser.getRmoney());
        mPayment.setPayStatus("1");
        mPayment.setContent(content);
        mPayment.setPayTime(new Date());
        mPayment.setPayDescribe(superRecordModel.getString("subject") == null ? "余额支付" : superRecordModel.getString("subject"));
        mPayment.setPayActualMoney(pmoney);
        mPaymentService.insert(mPayment);
        //订单更新
        updateOrderByOrderId(orderId, 1);
        //如果有优惠券使用,没有跳过
        if (StringUtils.isNotEmpty(coupon_id) && StringUtils.isNotEmpty(csid)) {
            useCouponByUserAndCouponId(csid, coupon_id, user.getSid());
        }
        //系统分销收益分发
        //一级用户
        //userProceeds(user.getSid(), orderId, orderMoney.doubleValue());

    }

    @Override
    @Transactional
    public void userProceeds(String userId, String orderId, Double orderMoney) {
        //一级用户
        MPromotion mPromotion1 = promotionService.getSuperUserByFromUser(userId);
        if ((null != mPromotion1) && (StringUtils.isNotEmpty(mPromotion1.getHostUser()))) {
            String oneUserId = mPromotion1.getHostUser();
            Double oneMoney = BigDecimalUtil.getMultiply(orderMoney, SystemConstant.ONE_USER_PROCEEDS_INTEREST);
            User oneUser = getUserBySid(oneUserId);
            if (oneUser == null) {
                return;
            }
            oneUser.setProceedsMoney(BigDecimalUtil.getAdd(oneUser.getProceedsMoney(), oneMoney));
            oneUser.setTotalProceedsMoney(BigDecimalUtil.getAdd(oneUser.getTotalProceedsMoney(), oneMoney));
            updateUserProceeds(oneUser);
            logger.info("【" + userId + "】的订单id：" + orderId + " 产生佣金:" + oneMoney + " 元给【" + oneUser.getTel() + "】一级用户");
            FProceedsRecord oneUserProceeds = new FProceedsRecord();
            oneUserProceeds.setSid(ObjectId.UUID());
            oneUserProceeds.setUserId(userId);
            oneUserProceeds.setOrderId(orderId);
            oneUserProceeds.setOrderMoney(orderMoney);
            oneUserProceeds.setOneUserId(oneUserId);
            oneUserProceeds.setOneMoney(oneMoney);
            oneUserProceeds.setcTime(new Date());
            try {
                int insert = proceedsDao.insert(oneUserProceeds);
            } catch (Exception e) {
                logger.debug(userId + "||一级用户oneUserId:" + oneUserId + "分销记录数据异常", e);
                e.printStackTrace();
            }
            //二级用户
            MPromotion mPromotion2 = promotionService.getSuperUserByFromUser(oneUserId);
            if ((mPromotion2 != null) && (StringUtils.isNotEmpty(mPromotion2.getHostUser()))) {
                String twoUserId = mPromotion2.getHostUser();
                Double twoMoney = BigDecimalUtil.getMultiply(orderMoney.doubleValue(), SystemConstant.TWO_USER_PROCEEDS_INTEREST);
                User twoUser = getUserBySid(twoUserId);
                twoUser.setProceedsMoney(BigDecimalUtil.getAdd(twoUser.getProceedsMoney().doubleValue(), twoMoney));
                twoUser.setTotalProceedsMoney(BigDecimalUtil.getAdd(twoUser.getTotalProceedsMoney().doubleValue(), twoMoney));
                updateUserProceeds(twoUser);
                logger.info("【" + userId + "】的订单id：" + orderId + " 产生佣金:" + twoMoney + " 元给【" + twoUser.getTel() + "】二级用户");
                FProceedsRecord twoUserProceeds = new FProceedsRecord();
                twoUserProceeds.setSid(oneUserProceeds.getSid());
                twoUserProceeds.setUserId(userId);
                twoUserProceeds.setOrderId(orderId);
                twoUserProceeds.setOrderMoney(orderMoney.doubleValue());
                twoUserProceeds.setTwoUserId(twoUserId);
                twoUserProceeds.setTwoMoney(twoMoney);
                twoUserProceeds.setcTime(new Date());
                try {
                    proceedsDao.update(twoUserProceeds);
                } catch (Exception e) {
                    logger.debug(userId + "||二级用户twoUserId:" + twoUserId + "分销记录数据异常", e);
                    e.printStackTrace();
                }
            }
        } else {
            logger.info(userId + "无父级用户");
        }
    }

    /**
     * 更新用户当前收益和总收益
     *
     * @param user
     */
    public void updateUserProceeds(User user) {
        getSqlSession().update("com.iwop.moto.dao.UserMapper.updateUserPRoceedsMoneyBySid", user);
    }

    /**
     * 根据订单id更新订单状态
     *
     * @param orderId
     */
    public void updateOrderByOrderId(String orderId, Integer status) throws MyException {
        if (switchClientTypeByOrderId(orderId).equals("user")) {
            SuperRecordModel userOrder = orderServiceService.getStoreOrderByOrderNo(orderId);
            userOrder.put("pushstatus", status);//支付完成
            userOrder.put("status_time", new Date());
            orderServiceService.updateStoreOrder(userOrder);

        } else if (switchClientTypeByOrderId(orderId).equals("business")) {
            MOrderPurchase mOrderPurchase = mOrderPurchaseService.findOneByOrderId(orderId);
            mOrderPurchase.setPayOrderNo(orderId);
            mOrderPurchase.setStatus(status);
            mOrderPurchase.setUpdateTime(new Date());
            mOrderPurchaseService.updateOrderPurchase(mOrderPurchase);

        } else if (switchClientTypeByOrderId(orderId).equals("Ho")) {
            MGPOrder mgpOrder = mgpOrderService.findOneBySid(orderId);
            mgpOrder.setOrderNo(orderId);
            mgpOrder.setStatusFlag("" + status);
            mgpOrder.setStatusTime(new Date());
            mgpOrderService.updateMGPOrder(mgpOrder);
        } else {
            logger.error(orderId + "==========订单号错误==========");
            throw new MyException(orderId + "===========订单号错误=== ========");
        }

    }

    /**
     * 判断订单类型
     *
     * @param OrderId
     * @return
     */
    public String switchClientTypeByOrderId(String OrderId) {
        String str = OrderId.substring(0, 2);
        String clientType;
        switch (str) {
            case "SO":
                clientType = "user";
                break;
            case "Co":
                clientType = "business";
                break;
            case "Ho":
                clientType = "Ho";
                break;
            default:
                clientType = "other";
        }
        return clientType;
    }

    /**
     * 优惠券使用
     *
     * @param coupon_id
     * @param user
     * @return
     */
    @Transactional
    public void useCouponByUserAndCouponId(String csid, String coupon_id, String user_id) {
        SuperRecordModel superRecordModel = new SuperRecordModel();
        superRecordModel.put("coupon_id", coupon_id);
        superRecordModel.put("user_id", user_id);
        superRecordModel.put("sid", csid);
        SuperRecordModel coupon = mCouponService.findUserCouponBySidAndUserId(superRecordModel);
        if (coupon == null) {
            logger.error("优惠券id错误:" + coupon_id);
        }
        try {
            updateUserCoupon(user_id, coupon);
        } catch (Exception e) {
            logger.error("用户更新优惠券失败", e);
        }
    }

    /**
     * 用户优惠券更改状态 status_flag 1未使用 ,2使用
     *
     * @param user
     * @param coupon
     */
    private void updateUserCoupon(String user_id, SuperRecordModel coupon) {
        coupon.put("status_flag", 2);
        coupon.put("status_time", new Date());
        coupon.put("user_id", user_id);
        mCouponService.updateUserCouponStatusBySid(coupon);
    }


    @Override
    public PromotionVo findUserPromotionByUserId(String userId) {
        PromotionVo promotionVo = new PromotionVo();
        List<String> childsUser = new ArrayList<>();
        try {
            childsUser = promotionService.getChildUsersByhostUser(userId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询一级用户id异常",e);
        }
        if (childsUser.size() != 0) {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            promotionVo.setChildUserTean(childsUser.size()); //一级用户人数
            int childsChildCount = 0;
            for (String childId : childsUser) {
                List<String> childsChilds = null;
                try {
                    childsChilds = promotionService.getChildUsersByhostUser(childId);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("查询二级用户id异常",e);
                }
                childsChildCount = childsChildCount + childsChilds.size();
            }
            promotionVo.setChildsChildTean(childsChildCount);//二级用户人数
            User userBySid = this.getUserBySid(userId);
            if (userBySid != null) {
                promotionVo.setProceedsMoney(userBySid.getProceedsMoney());
                promotionVo.setTotalProceedsMoney(userBySid.getTotalProceedsMoney());
                return promotionVo;
            }
        }
        return null;
    }

    @Override
    @Transactional
    public Boolean cashUserProceedsMoney(String userId) {
        try {
            User user = new User();
            user.setSid(userId);
            User byUser = this.findUserByUser(user);
            Double proceedsMoney = byUser.getProceedsMoney();
            if (proceedsMoney <= 0) {
                return false;
            }

            MPayment mPayment = new MPayment();
            mPayment.setPayId(ObjectId.UUID());
            mPayment.setAddTime(new Date());
            mPayment.setPayStatus("1");
            mPayment.setContent("分销收益兑现");
            mPayment.setPayMoney(proceedsMoney);
            mPayment.setOriginalTmoney(byUser.getRmoney());
            mPayment.setModifyTmoney(BigDecimalUtil.getAdd(byUser.getRmoney(),proceedsMoney));
            mPayment.setMchType("PLATFORM");//平台
            mPayment.setMchId("MB");//
            mPayment.setOutTradeNo(SequenceUtil.Serial("PO"));
            mPayment.setPayDescribe("分销收入转入余额");
            mPayment.setPayActualMoney(proceedsMoney);
            mPayment.setAddTime(new Date());
            mPayment.setPayType("Profit");
            mPayment.setBuyerUserId(userId);
            mPayment.setSellerUserId(userId);
            mPayment.setPayTime(new Date());
            getSqlSession().insert("MPaymentMapper.insert", mPayment);

            byUser.setRmoney(BigDecimalUtil.getAdd(byUser.getRmoney(),proceedsMoney));
            byUser.setProceedsMoney(BigDecimalUtil.getSubtract(byUser.getProceedsMoney(), proceedsMoney));
            this.save(byUser);
        } catch (Exception e) {
            logger.error("系统错误", e);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public List<SuperRecordModel> findEnterStoresListByMap(SuperRecordModel srm) {
        return getSqlSession().selectList(findEnterStoresListByMap, srm);
    }

    @Override
    public SuperRecordModel findEnterStoresListDetailByMap(SuperRecordModel srm) {
        return getSqlSession().selectOne(findEnterStoresListDetailByMap, srm);
    }

    @Override
    public List<SuperRecordModel> findEnterStoresListExportByMap(SuperRecordModel srm) {
        return getSqlSession().selectList(findenterStoresExportListByMap, srm);
    }

    @Override
    public Long findEnterStoresListByMapCount(SuperRecordModel srm) {
        return getSqlSession().selectOne(findEnterStoresListByMapCount, srm);
    }
}